<template>
  <el-form
    ref="comTcpRef"
    :model="ruleForm"
    label-width="80px"
    class="price-tcp edit-form-wrap"
  >
    <el-form-item label="价格类别" class="bottom-wrap" required>
      <Combination
        ref="comTypeRef"
        :items="typeItem"
        :comData="ruleForm.types"
        :rules="typeRules"
        :size="4"
        @updatas="updatasType"
        @data-minus="dataMinusType"
      ></Combination>
    </el-form-item>
    <el-form-item v-if="isTime" class="bottom-wrap" label="计费时段" required>
      <Combination
        ref="comTimeRef"
        :items="timeItem"
        :comData="ruleForm.times"
        :rules="timeRules"
      ></Combination>
    </el-form-item>
    <el-form-item v-if="isTime && isOther" label="" required>
      <Combination
        ref="comOtherRef"
        :items="otherItem"
        :comData="ruleForm.other"
        :rules="timeRules"
        :size="1"
        :ishidePM="true"
      ></Combination>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup name="price-tcp">
import { FormRules } from 'element-plus';
import Combination from '@/components/combination/combination.vue';
import { IS_DECIMAL_4 } from '@/utils/verify';
import { optionsP, visibleChangeStart, visibleChangeEnd } from './price';

interface Props {
  protocolVersion?: string;
}
const prop = withDefaults(defineProps<Props>(), {
  protocolVersion: '',
});

const comTypeRef = ref();
const comTimeRef = ref();
const comOtherRef = ref();
let options = reactive({
  sTimes: [] as any,
  eTimes: [] as any,
  types: [] as any,
});
options.sTimes = optionsP.sTimes;
options.eTimes = optionsP.eTimes;

let isTime = ref(false);
let isOther = ref(false);

const ruleForm = reactive({
  types: [] as any,
  times: [] as any,
  other: [] as any,
});

// 开始时间下拉是重置下拉数据
const visibleChangeS = (e: any, index: number, form: any) => {
  if (e) {
    visibleChangeStart(e, index, form);
    comTimeRef.value?.setOptions(index, 0, options.sTimes);
  }
};

// 结束时间下拉是重置下拉数据
const visibleChangeE = (e: any, index: number, form: any) => {
  if (e) {
    visibleChangeEnd(e, index, form);
    comTimeRef.value?.setOptions(index, 1, options.eTimes);
  }
};

// 价格类别下拉数据
const setOptionsType = (data: any) => {
  options.types = [];
  data.forEach((item: any, inx: number) => {
    if (item.typeName && item.pricePower && item.priceService) {
      options.types.push({
        value: String(inx + 1),
        label: `${item.typeName}：电费${item.pricePower}元/度，服务费${item.priceService}元/度`,
      });
    }
  });
};
const visibleChangeType = (e: any, index: number, form: any) => {
  const data = comTypeRef?.value?.getData();
  setOptionsType(data);
  if (options.types.length > 0) {
    const len = form.items[0].length;
    if (len === 3) {
      comTimeRef.value?.setOptions(index, 2, options.types);
    } else if (len === 2) {
      comOtherRef.value?.setOptions(index, 1, options.types);
    }
  }
};

// 类别名称唯一校验
const checkName = (rule: any, value: any, callback: any) => {
  const index = Number(rule.field.split('.[')[1].split(']')[0]);
  const form = comTypeRef.value?.getData();
  const len = form.length;
  for (let i = 0; i < len; i++) {
    const item: any = form[i];
    if (index !== i && item.typeName === value) {
      callback(new Error('类别名称不能重复'));
      break;
    }
  }
  // let arr = [] as any;
  // form.forEach((item: any, inx: number) => {
  //   if (index !== inx && item.typeName === value) {
  //     arr.push(inx);
  //   }
  // });
  // if (arr.length > 0) {
  //   console.log(rule);
  //   console.log(comTypeRef.value?.validateField('data.[0][typeName]'));
  //   arr.forEach((item: number) => {});
  //   callback(new Error('类别名称不能重复'));
  // }
  callback();
};

// 判断是否覆盖24小时，覆盖就隐藏剩余时间，不能再增加
const checkTime = (rule: any, value: any, callback: any) => {
  const index = rule.field.split('.[')[1].split(']')[0];
  const form = comTimeRef.value?.getData();
  let arr = [] as any;
  form.forEach((item: any, inx: number) => {
    if (index !== inx) {
      for (let i = Number(item.startTime); i < Number(item.endTime); i++) {
        arr.push(i);
      }
    }
  });
  if (arr.length >= 48) {
    comTimeRef.value?.setFlagAdd(true);
    isOther.value = false;
  } else {
    comTimeRef.value?.setFlagAdd(false);
    isOther.value = true;
  }
  callback();
};

const typeItem = reactive([
  {
    comName: 'input',
    // label: '类别名称',
    label: '',
    labelWidth: 0,
    prop: 'typeName',
    width: 240,
    props: {
      prepend: '类别名称',
      maxlength: 10,
      placeholder: '请输入类别名称',
    },
  },
  {
    comName: 'input',
    // label: '电费',
    label: '',
    labelWidth: 0,
    prop: 'pricePower',
    width: 240,
    props: {
      prepend: '电费',
      append: '元/度',
      maxlength: 10,
      placeholder: '精确到4位小数',
    },
  },
  {
    comName: 'input',
    // label: '服务费',
    label: '',
    labelWidth: 0,
    prop: 'priceService',
    width: 240,
    props: {
      prepend: '服务费',
      append: '元/度',
      maxlength: 10,
      placeholder: '精确到4位小数',
    },
  },
]);
const timeItem = reactive([
  {
    comName: 'select',
    // label: '开始时间',
    label: '',
    labelWidth: 0,
    prop: 'startTime',
    width: 172,
    props: {
      clearable: false,
      prepend: '开始时间',
      options: options.sTimes,
      visibleChange: visibleChangeS,
    },
  },
  {
    comName: 'select',
    // label: '结算时间',
    label: '',
    labelWidth: 0,
    prop: 'endTime',
    width: 172,
    props: {
      clearable: false,
      prepend: '结束时间',
      options: options.eTimes,
      visibleChange: visibleChangeE,
    },
  },
  {
    comName: 'select',
    // label: '价格类别',
    label: '',
    labelWidth: 0,
    prop: 'type',
    width: 172,
    props: {
      prepend: '价格类别',
      options: options.types,
      visibleChange: visibleChangeType,
    },
  },
]);

const otherItem = reactive([
  {
    comName: 'input',
    label: '',
    labelWidth: 0,
    prop: 'time',
    width: 492,
    props: {
      disabled: true,
      maxlength: 10,
      placeholder: '剩余时段价格统一设置',
    },
  },
  {
    comName: 'select',
    // label: '价格类别',
    label: '',
    labelWidth: 0,
    prop: 'type',
    width: 172,
    props: {
      prepend: '价格类别',
      options: options.types,
      visibleChange: visibleChangeType,
    },
  },
]);
const typeRules = reactive<FormRules>({
  typeName: [
    { required: true, message: '请输入类别名称', trigger: 'blur' },
    { validator: checkName, trigger: 'blur' },
  ],
  pricePower: [
    { required: true, message: '请输入电费', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '请输入正确的电费，精确到4位小数',
      trigger: 'blur',
    },
  ],
  priceService: [
    { required: true, message: '请输入服务费', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '请输入正确的电费，精确到4位小数',
      trigger: 'blur',
    },
  ],
});
const timeRules = reactive<FormRules>({
  startTime: [
    { required: true, message: '请选择开始时间', trigger: ['blur', 'change'] },
    { validator: checkTime, trigger: 'change' },
  ],
  endTime: [
    { required: true, message: '请选择结算时间', trigger: ['blur', 'change'] },
    { validator: checkTime, trigger: 'change' },
  ],
  type: [
    { required: true, message: '请选择价格类别', trigger: ['blur', 'change'] },
  ],
});

// 根据类别数据判断是否显示计费时段
const updatasType = (data: any) => {
  if (data.length > 1) {
    isTime.value = true;
    const form = comTimeRef.value?.getData() || [];
    let arr = [] as any;
    form.forEach((item: any, inx: number) => {
      if (item.startTime && item.endTime) {
        for (let i = Number(item.startTime); i < Number(item.endTime); i++) {
          arr.push(i);
        }
      }
    });
    if (arr.length >= 48) {
      isOther.value = false;
    } else {
      isOther.value = true;
    }
  } else {
    isTime.value = false;
    isOther.value = false;
  }
};

// 删除已选类别，清除选中数据
const dataMinusType = (index: number) => {
  const data = comTimeRef?.value.getData();
  data.forEach((item: any) => {
    if (item.type === String(index + 1)) {
      item.type = '';
    }
  });
  options.types.splice(index, 1);
};

const getData = async () => {
  if (!comTypeRef.value) return;
  const types = comTypeRef.value?.getData();
  const len = types.length;
  if (len > 1 && !comTimeRef.value) return;
  try {
    if (len === 1) {
      await Promise.all([comTypeRef.value.validate()]);
    } else if (comOtherRef.value) {
      await Promise.all([
        comTypeRef.value.validate(),
        comTimeRef.value.validate(),
        comOtherRef.value.validate(),
      ]);
    } else {
      await Promise.all([
        comTypeRef.value.validate(),
        comTimeRef.value.validate(),
      ]);
    }
  } catch (fields: any) {
    for (const key in fields) {
      if (fields[key]) {
        comTypeRef.value.scrollToField(key);
        break;
      }
    }
    return false;
  }
  const arrType = [] as any;
  const arrTime = [] as any;
  if (len === 1) {
    types.forEach((item: any, inx: number) => {
      arrType.push({
        protocolVersion: prop.protocolVersion, // 协议版本
        identification: inx + 1, // 标识（1、2、3、4、5）
        typeName: item.typeName,
        pricePower: item.pricePower,
        priceService: item.priceService,
      });
      arrTime.push({
        protocolVersion: prop.protocolVersion, // 协议版本
        isTimeRemaining: false, //是否剩余时间段 1： true 0： false
        startTime: 0,
        endTime: 48,
        startTimeStr: '00:00',
        endTimeStr: '24:00',
        priceTypeName: item.typeName,
      });
    });
  } else {
    const times = comTimeRef.value?.getData();

    types.forEach((item: any, inx: number) => {
      arrType.push({
        protocolVersion: prop.protocolVersion, // 协议版本
        identification: inx + 1, // 标识（1、2、3、4、5）
        typeName: item.typeName,
        pricePower: item.pricePower,
        priceService: item.priceService,
      });
    });
    times.forEach((item: any, inx: number) => {
      arrTime.push({
        protocolVersion: prop.protocolVersion, // 协议版本
        isTimeRemaining: false, //是否剩余时间段 1： true 0： false
        startTime: item.startTime,
        endTime: item.endTime,
        startTimeStr: options.sTimes.find(
          (temp: any) => temp.value === item.startTime
        ).label,
        endTimeStr: options.eTimes.find(
          (temp: any) => temp.value === item.endTime
        ).label,
        priceTypeName: types[Number(item.type) - 1].typeName,
      });
    });
    if (comOtherRef.value) {
      const order = comOtherRef.value?.getData();
      arrTime.push({
        protocolVersion: prop.protocolVersion, // 协议版本
        isTimeRemaining: true, //是否剩余时间段 1： true 0： false
        startTime: 99,
        endTime: 99,
        startTimeStr: '',
        endTimeStr: '',
        priceTypeName: types[Number(order[0].type) - 1].typeName,
      });
    }
  }

  return { type: arrType, time: arrTime };
};

const setData = (type: any, time: any) => {
  ruleForm.types = [];
  ruleForm.times = [];
  ruleForm.other = [];
  type.forEach((item: any) => {
    ruleForm.types.push({
      typeName: item.typeName,
      pricePower: String(item.pricePower),
      priceService: String(item.priceService),
    });
  });
  if (type.length > 1) {
    setOptionsType(ruleForm.types);
    time.forEach((item: any, index: number) => {
      const inx = ruleForm.types.findIndex(
        (it: any) => it.typeName === item.priceTypeName
      );
      if (item.isTimeRemaining) {
        ruleForm.other.push({
          type: String(inx + 1),
        });
        nextTick(() => {
          comOtherRef.value?.setOptions(0, 1, options.types);
        });
      } else {
        nextTick(() => {
          comTimeRef.value?.setOptions(index, 2, options.types);
        });
        ruleForm.times.push({
          startTime: String(item.startTime),
          endTime: String(item.endTime),
          type: String(inx + 1),
        });
      }
    });
    nextTick(() => {
      if (ruleForm.other.length > 0) {
        comTimeRef.value?.setFlagAdd(false);
        isOther.value = true;
      } else {
        comTimeRef.value?.setFlagAdd(true);
        isOther.value = false;
      }
    });
  }
};

defineExpose({
  getData,
  setData,
});
</script>